package com.chp.demo5.business.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chp.demo5.business.entity.RzAcctDatabaseInfo;
import com.chp.demo5.business.mapper.RzAcctDatabaseInfoMapper;
import com.chp.demo5.business.mapper.UserMapper;
import com.chp.demo5.common.datasource.DataSourceContextHolder;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@Service
public class AcctReportService {

    @Autowired
    RzAcctDatabaseInfoMapper rzAcctDatabaseInfoMapper;

    @Autowired
    ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    UserMapper userMapper;
;
    public void testAcctReport(){
        List<RzAcctDatabaseInfo> list = rzAcctDatabaseInfoMapper.selectList(new QueryWrapper<>());
        List<CompletableFuture> completableFutureList = Lists.newArrayList();
        for(RzAcctDatabaseInfo rzAcctDatabaseInfo: list) {
            //开启异步任务1
            CompletableFuture<Integer> task = CompletableFuture.supplyAsync(() -> {
                System.out.println("异步任务1，当前线程是：" + Thread.currentThread().getId());
                DataSourceContextHolder.setDataSource(rzAcctDatabaseInfo.getDomain()+rzAcctDatabaseInfo.getAcctId());
                Integer result = userMapper.countVoucher();
                System.out.println("异步任务1结束"+result);
                return result;
            }, threadPoolTaskExecutor);
            completableFutureList.add(task);
        }

        try  {
            //多个任务
            CompletableFuture[] futureArray = completableFutureList.toArray(new CompletableFuture[0]);
            //将多个任务，汇总成一个任务，总共耗时不超时2秒
            //任务组合
            //Void allOf = CompletableFuture.allOf(futureArray).get(20, TimeUnit.SECONDS);
            Void allOf = CompletableFuture.allOf(futureArray).get();
            List<Integer> result2= Lists.newArrayList();
            int size = futureArray.length;
            for(int i=0;i<size;i++){
                System.out.println("====================="+futureArray[i].get());
                result2.add((Integer) futureArray[i].get());
            }
            System.out.println(result2.stream().reduce(0,(x,y)->x+y));
        } catch (Exception e) {
            System.out.println("CompletableFuture.allOf Exception error.");
            e.printStackTrace();
        }
    }
}
